package com.zut.chat.controller;

import com.zut.chat.dto.WebSocketMessage;
import com.zut.chat.entity.User;
import com.zut.chat.service.ChatWebSocketService;
import com.zut.chat.service.UserService;
import com.zut.chat.service.SysUserService;
import com.zut.chat.util.DateTimeUtils;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 管理员控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/admin")
public class AdminController {

    @Autowired
    private UserService userService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ChatWebSocketService chatWebSocketService;

        /**
     * 获取在线用户列表（所有用户都可以访问）
     */
    @GetMapping("/online-users")
    public ResponseEntity<?> getOnlineUsers(
            @RequestParam(required = false) String nickname,
            @RequestParam String sessionId) {

        // 对于临时会话或未登录用户，也允许查看在线用户列表
        User currentUser = userService.findBySessionId(sessionId);
        boolean isAdmin = currentUser != null && User.UserType.ADMIN.equals(currentUser.getUserType());

        try {
            List<User> onlineUsers = userService.searchOnlineUsers(nickname);

            List<WebSocketMessage.OnlineUserInfo> userInfoList = onlineUsers.stream()
                    .map(user -> WebSocketMessage.OnlineUserInfo.builder()
                            .sessionId(user.getSessionId())
                            .nickname(user.getNickname())
                            .userType(user.getUserType().name())
                            .lastActiveTime(user.getLastActiveTime())
                            .build())
                    .collect(Collectors.toList());

            // 使用之前计算的管理员状态

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", userInfoList);
            response.put("total", userInfoList.size());
            response.put("isAdmin", isAdmin);

            return ResponseEntity.ok(response);
                } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取在线用户列表失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 踢出用户
     */
    @PostMapping("/kick-user")
    public ResponseEntity<?> kickUser(
            @RequestBody Map<String, String> request) {

        String adminSessionId = request.get("adminSessionId");
        String targetSessionId = request.get("targetSessionId");
        String reason = request.get("reason");

                // 验证管理员权限
        if (!userService.isAdmin(adminSessionId)) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "权限不足，仅管理员可以执行此操作");
            return ResponseEntity.status(403).body(errorResponse);
        }

        try {
                        // 获取目标用户信息
            User targetUser = userService.findBySessionId(targetSessionId);
            if (targetUser == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "目标用户不存在");
                return ResponseEntity.badRequest().body(errorResponse);
            }

                        // 不能踢出管理员
            if (User.UserType.ADMIN.equals(targetUser.getUserType())) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "不能踢出管理员用户");
                return ResponseEntity.badRequest().body(errorResponse);
            }

            // 强制用户下线
            boolean success = userService.forceUserOffline(targetSessionId);

            if (success) {
                // 向目标用户发送踢出消息
                WebSocketMessage kickMessage = WebSocketMessage.builder()
                        .type(WebSocketMessage.MessageType.ADMIN_KICK_USER)
                        .content("您已被管理员踢出聊天室" + (reason != null && !reason.trim().isEmpty() ? "，原因：" + reason : ""))
                        .timestamp(LocalDateTime.now())
                        .build();

                chatWebSocketService.sendMessageToUser(targetSessionId, kickMessage);

                // 广播用户被踢出的系统消息
                WebSocketMessage systemMessage = WebSocketMessage.builder()
                        .type(WebSocketMessage.MessageType.SYSTEM)
                        .content(targetUser.getNickname() + " 被管理员踢出了聊天室")
                        .timestamp(LocalDateTime.now())
                        .onlineCount(chatWebSocketService.getOnlineCount())
                        .build();

                chatWebSocketService.broadcastMessage(systemMessage);

                // 移除WebSocket会话
                chatWebSocketService.removeSession(targetSessionId);

                Map<String, Object> successResponse = new HashMap<>();
                successResponse.put("success", true);
                successResponse.put("message", "用户 " + targetUser.getNickname() + " 已被踢出");
                return ResponseEntity.ok(successResponse);
                        } else {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "踢出用户失败");
                return ResponseEntity.status(500).body(errorResponse);
            }
                } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "踢出用户失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 设置用户为管理员
     */
    @PostMapping("/set-admin")
    public ResponseEntity<?> setUserAsAdmin(
            @RequestBody Map<String, String> request) {

        String adminSessionId = request.get("adminSessionId");
        String targetSessionId = request.get("targetSessionId");

                // 验证管理员权限（允许临时管理员设置权限用于初始化）
        if (!userService.isAdmin(adminSessionId) && !adminSessionId.startsWith("admin-setup-")) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "权限不足，仅管理员可以执行此操作");
            return ResponseEntity.status(403).body(errorResponse);
        }

        try {
                        User targetUser = userService.findBySessionId(targetSessionId);
            if (targetUser == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "目标用户不存在");
                return ResponseEntity.badRequest().body(errorResponse);
            }

            boolean success = userService.setUserAsAdmin(targetSessionId);

                        if (success) {
                Map<String, Object> successResponse = new HashMap<>();
                successResponse.put("success", true);
                successResponse.put("message", "用户 " + targetUser.getNickname() + " 已设置为管理员");
                return ResponseEntity.ok(successResponse);
            } else {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "设置管理员失败");
                return ResponseEntity.status(500).body(errorResponse);
            }
                } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "设置管理员失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 禁言用户
     */
    @PostMapping("/ban-user")
    public ResponseEntity<?> banUser(@RequestBody Map<String, Object> request) {
        try {
            String adminSessionId = (String) request.get("adminSessionId");
            String targetSessionId = (String) request.get("targetSessionId");
            String reason = (String) request.get("reason");
            Integer banHours = (Integer) request.get("banHours");

            // 验证后台管理员权限（这里简化处理，实际应该通过Session或JWT Token验证）
            // TODO: 实际项目中应该从Session或Token中获取当前登录的后台管理员信息
            // 这里暂时使用简单的验证方式，实际使用时需要完善权限验证
            if (adminSessionId == null || adminSessionId.trim().isEmpty()) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "管理员会话ID不能为空");
                return ResponseEntity.status(403).body(errorResponse);
            }

            // 简化验证：检查是否是有效的管理员会话
            // 实际项目中应该验证Session中的SysUser信息
            if (!isValidAdminSession(adminSessionId)) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "权限不足，只有后台管理员才能禁言用户");
                return ResponseEntity.status(403).body(errorResponse);
            }

            // 检查目标用户
            User targetUser = userService.findBySessionId(targetSessionId);
            if (targetUser == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "目标用户不存在");
                return ResponseEntity.status(404).body(errorResponse);
            }

            // 不能禁言管理员
            if (User.UserType.ADMIN.equals(targetUser.getUserType())) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "不能禁言管理员用户");
                return ResponseEntity.status(400).body(errorResponse);
            }

            // 计算禁言到期时间
            LocalDateTime banExpireTime = null;
            if (banHours != null && banHours > 0) {
                banExpireTime = LocalDateTime.now().plusHours(banHours);
            }

            String banReason = reason != null ? reason.trim() : "违规行为";
            boolean success = userService.banUser(targetSessionId, banReason, banExpireTime);

            if (success) {
                // 向目标用户发送禁言通知
                String banMessage = "您已被管理员禁言，原因：" + banReason;
                if (banExpireTime != null) {
                    banMessage += "，解禁时间：" + DateTimeUtils.formatDateTime(banExpireTime);
                } else {
                    banMessage += "（永久禁言）";
                }

                WebSocketMessage banNotification = WebSocketMessage.builder()
                        .type(WebSocketMessage.MessageType.SYSTEM)
                        .content(banMessage)
                        .timestamp(LocalDateTime.now())
                        .build();

                chatWebSocketService.sendMessageToUser(targetSessionId, banNotification);

                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "用户 " + targetUser.getNickname() + " 已被禁言");
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "禁言操作失败");
                return ResponseEntity.status(500).body(errorResponse);
            }

        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "禁言用户失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 解除禁言
     */
    @PostMapping("/unban-user")
    public ResponseEntity<?> unbanUser(@RequestBody Map<String, Object> request) {
        try {
            String adminSessionId = (String) request.get("adminSessionId");
            String targetSessionId = (String) request.get("targetSessionId");

            // 验证后台管理员权限
            if (!isValidAdminSession(adminSessionId)) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "权限不足，只有后台管理员才能解除禁言");
                return ResponseEntity.status(403).body(errorResponse);
            }

            // 检查目标用户
            User targetUser = userService.findBySessionId(targetSessionId);
            if (targetUser == null) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "目标用户不存在");
                return ResponseEntity.status(404).body(errorResponse);
            }

            boolean success = userService.unbanUser(targetSessionId);

            if (success) {
                // 向目标用户发送解禁通知
                WebSocketMessage unbanNotification = WebSocketMessage.builder()
                        .type(WebSocketMessage.MessageType.SYSTEM)
                        .content("您的禁言已被管理员解除，可以正常聊天了")
                        .timestamp(LocalDateTime.now())
                        .build();

                chatWebSocketService.sendMessageToUser(targetSessionId, unbanNotification);

                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "用户 " + targetUser.getNickname() + " 的禁言已解除");
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "解除禁言操作失败");
                return ResponseEntity.status(500).body(errorResponse);
            }

        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "解除禁言失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 获取被禁言的用户列表
     */
    @GetMapping("/banned-users")
    public ResponseEntity<?> getBannedUsers(@RequestParam String adminSessionId) {
        try {
            // 验证后台管理员权限
            if (!isValidAdminSession(adminSessionId)) {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "权限不足，只有后台管理员才能查看禁言用户列表");
                return ResponseEntity.status(403).body(errorResponse);
            }

            List<User> bannedUsers = userService.getBannedUsers();

            List<Map<String, Object>> userInfoList = bannedUsers.stream()
                    .map(user -> {
                        Map<String, Object> userInfo = new HashMap<>();
                        userInfo.put("sessionId", user.getSessionId());
                        userInfo.put("nickname", user.getNickname());
                        userInfo.put("userType", user.getUserType().name());
                        userInfo.put("banned", user.getBanned());
                        userInfo.put("banReason", user.getBanReason());
                        userInfo.put("banExpireTime", user.getBanExpireTime());
                        userInfo.put("createTime", user.getCreateTime());
                        userInfo.put("lastActiveTime", user.getLastActiveTime());
                        return userInfo;
                    })
                    .collect(Collectors.toList());

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", userInfoList);
            response.put("message", "获取禁言用户列表成功");

            return ResponseEntity.ok(response);

        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取禁言用户列表失败：" + e.getMessage());
            return ResponseEntity.status(500).body(errorResponse);
        }
    }

    /**
     * 验证是否是有效的后台管理员会话
     * 通过查询数据库中的SysUser表来验证管理员身份
     */
    private boolean isValidAdminSession(String adminSessionId) {
        try {
            // 临时方案：允许特定的管理员会话ID（用于测试）
            if ("admin-session-id".equals(adminSessionId)) {
                return true;
            }

            // 如果adminSessionId实际上是用户名，直接查询数据库验证
            // 检查用户名是否为"admin"且用户状态正常
            if ("admin".equals(adminSessionId)) {
                // 查询数据库中用户名为"admin"的SysUser
                var adminUser = sysUserService.findByUsername("admin");
                if (adminUser != null && adminUser.getStatus() == 1) {
                    return true;
                }
            }

            // 也可以通过用户名查询来验证
            var sysUser = sysUserService.findByUsername(adminSessionId);
            if (sysUser != null && "admin".equals(sysUser.getUsername()) && sysUser.getStatus() == 1) {
                return true;
            }

            return false;

        } catch (Exception e) {
            log.error("验证管理员会话时发生错误: {}", e.getMessage());
            return false;
        }
    }
}
